﻿Imports Odyssee.WebControles

Public Class FicheEntreprise
    Inherits FichePage(Of String, ServiceEntreprises.Entreprise, ServiceEntreprises.EntreprisesClient, ServiceEntreprises.CriteresRechercheEntreprise)

    Public Overrides ReadOnly Property Titre As String
        Get
            Return "Fiche entreprise"
        End Get
    End Property
    Protected Overrides ReadOnly Property LibelleEntite As String
        Get
            Return "entreprise"
        End Get
    End Property
    Protected Overrides ReadOnly Property LibelleFeminin As Boolean
        Get
            Return True
        End Get
    End Property
    Protected Overrides ReadOnly Property LibelleApostrophe As Boolean
        Get
            Return True
        End Get
    End Property
    Protected Overrides ReadOnly Property PopupPanel As JQPopupPanel
        Get
            Return Me.pnlEntreprise
        End Get
    End Property
    Protected Overrides ReadOnly Property BoutonActualiser As Button
        Get
            Return Me.btnActualiser
        End Get
    End Property
    Protected Overrides ReadOnly Property SeparateurActualiser As ToolBarSeparator
        Get
            Return Me.tbSep1
        End Get
    End Property
    Protected Overrides ReadOnly Property BoutonEnregistrer As Button
        Get
            Return Me.btnEnregister
        End Get
    End Property


    Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Me.CtrlAdresse.Initialiser()

        If IsPostBack Then
            If Request.Form("__EVENTTARGET") = "btnAjouterContact" Then
                Me.pnlEntreprise.ShowPopup("~/Tiers/LienEntrepriseContact.aspx", "&cleContact=" & Request.Form("ctl00$content$pnlEntreprise__hidden1") & "&cleEntreprise=" & Server.UrlEncode(Me.CleEntite), ,,,,,,,,,,, True, , , , "Lien entreprise / contact", "600", "720")
            ElseIf Request.Form("__EVENTTARGET") = "content_pnlEntreprise__button" Then
                InitialiserLiensContacts()
            End If
        ElseIf Me.ModeFiche = Tools.ModeFiche.Creation Then
            SetFocus(Me.txtNom)
        ElseIf Me.ModeFiche = Tools.ModeFiche.Modification Then
            SetFocus(Me.cmbType)
        End If
    End Sub

    Private Sub gvContacts_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles gvContacts.RowCommand
        Dim cleContact As Integer = 0
        Dim fonction As String = ""

        If e.CommandArgument Is Nothing Then Return
        fonction = CStr(e.CommandArgument)
        If fonction.Contains("¤") Then
            If Not IsNumeric(fonction.Split("¤"c)(0)) Then Return
            cleContact = CInt(fonction.Split("¤"c)(0))
            fonction = fonction.Split("¤"c)(1)
        ElseIf IsNumeric(fonction) Then
            cleContact = CInt(fonction)
            fonction = ""
        Else
            Return
        End If

        Select Case e.CommandName.ToUpper
            Case "MODIFIER"
                Response.Redirect("~/Tiers/FicheContact.aspx?modeFiche=1&cle=" & cleContact.ToString)

            Case "SUPPRIMER"
                SupprimerLienContact(cleContact, fonction)

        End Select
    End Sub


    Protected Overrides Function InitialiserCriteresRechercheEntite(cle As String) As ServiceEntreprises.CriteresRechercheEntreprise
        Dim criteres As New ServiceEntreprises.CriteresRechercheEntreprise
        criteres.Authentication = New ServiceEntreprises.AuthenticationParameters
        criteres.Authentication.Token = Tools.GetInstance.getToken
        criteres.Cle = cle
        Return criteres
    End Function
    Protected Overrides Function RechercherEntite(svc As ServiceEntreprises.EntreprisesClient, criteres As ServiceEntreprises.CriteresRechercheEntreprise, ByRef ok As Boolean, ByRef messageErreur As String) As List(Of ServiceEntreprises.Entreprise)
        Dim results As ServiceEntreprises.ResultatRechercheEntreprise
        results = svc.Recherche(criteres)
        If results Is Nothing Then Return Nothing
        ok = results.OK
        messageErreur = results.ErrorMessage
        Return results.Entreprises
    End Function
    Protected Overrides Sub InitialiserObjetEntite(entite As ServiceEntreprises.Entreprise)
        If entite.Adresse Is Nothing Then entite.Adresse = New ServiceEntreprises.Adresse
        If entite.ZoneSup Is Nothing Then entite.ZoneSup = New ServiceEntreprises.ZoneSup
    End Sub

    Protected Overrides Sub InitialiserParametres()
        MyBase.InitialiserParametres()

        ' Chargement de la liste des types
        Dim result As String = Tools.LoadParametersCombo(Me.cmbType, "types d'entreprise", 6)
        If result <> "" Then
            NotifyErreur(result)
            Return
        End If
    End Sub


    Protected Overrides Sub InitialiserPage()
        MyBase.InitialiserPage()

        Select Case Me.ModeFiche

            Case Tools.ModeFiche.Creation
                Me.divContacts.Visible = False

            Case Tools.ModeFiche.Modification
                ' Contact
                Me.txtNom.Enabled = False
                Me.txtNom.Text = Me.Entite.Cle
                Me.cmbType.Text = Me.Entite.Type
                Me.CtrlAdresse.AffecterValeurs(Me.Entite.Adresse)
                Me.txtSIRET.Text = If(Me.Entite.CodeSIRET = 0, "", If(Me.Entite.CodeSIRET.ToString.Length = 9, Me.Entite.CodeSIRET.ToString("### ### ###"), If(Me.Entite.CodeSIRET.ToString.Length = 14, Me.Entite.CodeSIRET.ToString("### ### ### #####"), Me.Entite.CodeSIRET.ToString)))
                Me.txtAbrege.Text = Me.Entite.Abrege
                Me.txtTelephone.Text = Tools.FormaterNumeroTelephone(Me.Entite.Telephone)
                Me.txtFax.Text = Tools.FormaterNumeroTelephone(Me.Entite.Fax)
                Me.txtEMail.Text = Me.Entite.Email
                Me.txtSiteWeb.Text = Me.Entite.SiteWeb

                ' Entreprises
                InitialiserLiensContacts()

        End Select
    End Sub

    Private Sub InitialiserLiensContacts()
        Using svc As New ServiceContacts.ContactsClient
            Dim params As New ServiceContacts.ParametresLectureLienContactEntreprise
            params.Authentication = New ServiceContacts.AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken
            params.CleEntreprise = Me.CleEntite

            Dim results As ServiceContacts.ResultatListeLiensContactEntreprise = Nothing
            Try
                results = svc.LectureLiensContactEntreprise(params)
                If results Is Nothing OrElse Not results.OK Then
                    NotifyErreur("Impossible de charger les contacts de l'entreprise '" & Me.CleEntite & "'" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                Else
                    Me.gvContacts.DataSource = results.Liens
                    Me.gvContacts.DataBind()
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
            End Try
        End Using
    End Sub
    Protected Sub SupprimerLienContact(cleContact As Integer, fonction As String)
        Using svc As New ServiceContacts.ContactsClient
            Dim params As New ServiceContacts.ParametresLectureLienContactEntreprise
            params.Authentication = New ServiceContacts.AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken
            params.CleContact = cleContact
            params.CleEntreprise = Me.CleEntite
            params.Fonction = fonction

            Try
                Dim results As ServiceContacts.OperationResult
                results = svc.SupprimerLienContactEntreprise(params)
                If results.OK Then
                    NotifySuccess("Suppression effectuée avec succès.")
                    InitialiserLiensContacts()
                Else
                    NotifyErreur(results.ErrorMessage)
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
            End Try
        End Using
    End Sub


    Protected Overrides Function Renseigner() As Boolean
        Me.Entite.Cle = Me.txtNom.Text
        Me.Entite.Type = Me.cmbType.Text
        Me.Entite.Adresse.Pays = "FR"
        Me.CtrlAdresse.RecupererValeurs(Me.Entite.Adresse)
        Me.Entite.CodeSIRET = If(IsNumeric(Me.txtSIRET.Text.Replace(" ", "")), CLng(Me.txtSIRET.Text.Replace(" ", "")), 0)
        Me.Entite.Abrege = Me.txtAbrege.Text
        Me.Entite.Telephone = Me.txtTelephone.Text
        Me.Entite.Fax = Me.txtFax.Text
        Me.Entite.Email = Me.txtEMail.Text
        Me.Entite.SiteWeb = Me.txtSiteWeb.Text
        Return True
    End Function
    Protected Overrides Function Creer() As Boolean
        Dim cleEntreprise As String = ""

        ' Vérification de la commune
        If Not Me.CtrlAdresse.ValiderCommune() Then Return False

        ' Création de l'entreprise
        Using svc As New ServiceEntreprises.EntreprisesClient
            Dim params As New ServiceEntreprises.ParametresCreationEntreprise
            params.Authentication = New ServiceEntreprises.AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken
            params.Entreprise = Me.Entite

            Try
                Dim results As ServiceEntreprises.ResultatCreationEntreprise = svc.Creation(params)
                If results Is Nothing OrElse Not results.OK Then
                    NotifyErreur("Impossible de créer l'entreprise" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                    Return False
                Else
                    cleEntreprise = results.CleEntreprise
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
                Return False
            End Try
        End Using

        Me.Entite.Cle = cleEntreprise
        Me.CleEntite = cleEntreprise

        Return True
    End Function
    Protected Overrides Function MettreAJour() As Boolean
        ' Vérification de la commune
        If Not Me.CtrlAdresse.ValiderCommune() Then Return False

        ' Mise à jour du contact
        Using svc As New ServiceEntreprises.EntreprisesClient
            Dim params As New ServiceEntreprises.ParametresCreationEntreprise
            params.Authentication = New ServiceEntreprises.AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken
            params.Entreprise = Me.Entite

            Try
                Dim results As ServiceEntreprises.OperationResult = svc.MiseAJour(params)
                If results Is Nothing OrElse Not results.OK Then
                    NotifyErreur("Impossible de mettre à jour l'entreprise" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                    Return False
                Else
                    NotifySuccess("Entreprise mise à jour avec succès.")
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
                Return False
            End Try
        End Using

        Return True
    End Function

End Class